package com.example.wacoffee_manage.interceptor;

import cn.hutool.jwt.Claims;
import cn.hutool.jwt.JWTUtil;
import com.example.wacoffee_manage.utils.CurrentHoler;
import com.example.wacoffee_manage.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String url=request.getRequestURI().toString();
        if(url.contains("login")){
            log.info("登陆请求，放行");
            return true;
        }
        String token=request.getHeader("Authorization");
        if(token==null||token.equals("")){
            log.info("token为空，请重新登录");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        token=token.replace("Bearer ","");
        try{
            JWTUtil.parseToken(token);
        }catch (Exception e){
            e.printStackTrace();
            log.info("token解析失败，请重新登录");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        if(JwtUtil.isTokenExpired(token)){
            log.info("token已过期，请重新登录");
            System.out.println("token已过期");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        Claims claims=JWTUtil.parseToken(token).getPayload();
        Object id =  claims.getClaim("id");
        log.info("用户ID: {}", id);
        CurrentHoler.set(Integer.valueOf(id.toString()));
        return true;
    }
}